import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemUserApi } from '#/api/system/user';

import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { $t } from '@vben/locales';
import { handleTree } from '@vben/utils';

import { z } from '#/adapter/form';
import { getDeptList } from '#/api/system/dept';
import { getSimplePostList } from '#/api/system/post';
import { getSimpleRoleList } from '#/api/system/role';
import { getRangePickerDefaultProps } from '#/utils';

/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'id',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'username',
      label: $t('views.system.user.username'),
      component: 'Input',
      rules: 'required',
    },
    {
      label: $t('views.system.user.password'),
      fieldName: 'password',
      component: 'InputPassword',
      rules: 'required',
      dependencies: {
        triggerFields: ['id'],
        show: (values) => !values.id,
      },
    },
    {
      fieldName: 'nickname',
      label: $t('views.system.user.nickname'),
      component: 'Input',
      rules: 'required',
    },
    {
      fieldName: 'deptId',
      label: $t('views.system.user.deptId'),
      component: 'ApiTreeSelect',
      componentProps: {
        api: async () => {
          const data = await getDeptList();
          return handleTree(data);
        },
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: $t('views.system.user.deptIdPlaceholder'),
        treeDefaultExpandAll: true,
      },
    },
    {
      fieldName: 'postIds',
      label: $t('views.system.user.postId'),
      component: 'ApiSelect',
      componentProps: {
        api: getSimplePostList,
        labelField: 'name',
        valueField: 'id',
        mode: 'multiple',
        placeholder: $t('views.system.user.postIdPlaceholder'),
      },
    },
    {
      fieldName: 'email',
      label: $t('views.system.user.email'),
      component: 'Input',
      rules: z.string().email($t('views.system.user.emailInvalid')).or(z.literal('')).optional(),
      componentProps: {
        placeholder: $t('views.system.user.emailPlaceholder'),
      },
    },
    {
      fieldName: 'mobile',
      label: $t('views.system.user.mobile'),
      component: 'Input',
      componentProps: {
        placeholder: $t('views.system.user.mobilePlaceholder'),
      },
    },
    {
      fieldName: 'sex',
      label: $t('views.system.user.sex'),
      component: 'RadioGroup',
      componentProps: {
        options: getDictOptions(DICT_TYPE.SYSTEM_USER_SEX, 'number'),
        buttonStyle: 'solid',
        optionType: 'button',
      },
      rules: z.number().default(1),
    },
    {
      fieldName: 'status',
      label: $t('common.status'),
      component: 'RadioGroup',
      componentProps: {
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        buttonStyle: 'solid',
        optionType: 'button',
      },
      rules: z.number().default(CommonStatusEnum.ENABLE),
    },
    {
      fieldName: 'remark',
      label: $t('common.remark'),
      component: 'Textarea',
    },
  ];
}

/** 重置密码的表单 */
export function useResetPasswordFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'id',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        passwordStrength: true,
        placeholder: $t('views.system.user.newPasswordPlaceholder'),
      },
      dependencies: {
        rules(values) {
          return z
            .string({ message: $t('views.system.user.newPasswordRequired') })
            .min(5, $t('views.system.user.passwordMinLength'))
            .max(20, $t('views.system.user.passwordMaxLength'))
            .refine(
              (value) => value !== values.oldPassword,
              '新旧密码不能相同',
            );
        },
        triggerFields: ['newPassword', 'oldPassword'],
      },
      fieldName: 'newPassword',
      label: $t('views.system.user.newPassword'),
      rules: 'required',
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        passwordStrength: true,
        placeholder: $t('authentication.confirmPassword'),
      },
      dependencies: {
        rules(values) {
          return z
            .string({ message: $t('views.system.user.confirmPasswordRequired') })
            .min(5, $t('views.system.user.passwordMinLength'))
            .max(20, $t('views.system.user.passwordMaxLength'))
            .refine(
              (value) => value === values.newPassword,
              $t('views.system.user.confirmPasswordNotMatch'),
            );
        },
        triggerFields: ['newPassword', 'confirmPassword'],
      },
      fieldName: 'confirmPassword',
      label: $t('views.system.user.confirmPassword'),
      rules: 'required',
    },
  ];
}

/** 分配角色的表单 */
export function useAssignRoleFormSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'id',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'username',
      label: $t('views.system.user.username'),
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      fieldName: 'nickname',
      label: $t('views.system.user.nickname'),
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      fieldName: 'roleIds',
      label: $t('views.system.user.roleId'),
      component: 'ApiSelect',
      componentProps: {
        api: getSimpleRoleList,
        labelField: 'name',
        valueField: 'id',
        mode: 'multiple',
        placeholder: $t('views.system.user.roleIdPlaceholder'),
      },
    },
  ];
}

/** 用户导入的表单 */
export function useImportFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'file',
      label: $t('views.system.user.userFile'),
      component: 'Upload',
      rules: 'required',
      help: $t('views.system.user.userFileHelp'),
    },
    {
      fieldName: 'updateSupport',
      label: $t('views.system.user.updateSupport'),
      component: 'Switch',
      componentProps: {
        checkedChildren: $t('common.yes'),
        unCheckedChildren: $t('common.no'),
      },
      rules: z.boolean().default(false),
      help: $t('views.system.user.updateSupportHelp'),
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'username',
      label: $t('views.system.user.username'),
      component: 'Input',
      componentProps: {
        placeholder: $t('views.system.user.usernamePlaceholder'),
        allowClear: true,
      },
    },
    {
      fieldName: 'mobile',
      label: $t('views.system.user.mobile'),
      component: 'Input',
      componentProps: {
        placeholder: $t('views.system.user.mobilePlaceholder'),
        allowClear: true,
      },
    },
    {
      fieldName: 'createTime',
      label: $t('common.createTime'),
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns<T = SystemUserApi.User>(
  onStatusChange?: (
    newStatus: number,
    row: T,
  ) => PromiseLike<boolean | undefined>,
): VxeTableGridOptions['columns'] {
  return [
    { type: 'checkbox', width: 40 },
    {
      field: 'id',
      title: $t('views.system.user.id'),
      minWidth: 100,
    },
    {
      field: 'username',
      title: $t('views.system.user.username'),
      minWidth: 120,
    },
    {
      field: 'nickname',
      title: $t('views.system.user.nickname'),
      minWidth: 120,
    },
    {
      field: 'deptName',
      title: $t('views.system.user.deptId'),
      minWidth: 120,
    },
    {
      field: 'mobile',
      title: $t('views.system.user.mobile'),
      minWidth: 120,
    },
    {
      field: 'status',
      title: $t('common.status'),
      minWidth: 100,
      align: 'center',
      cellRender: {
        attrs: { beforeChange: onStatusChange },
        name: 'CellSwitch',
        props: {
          checkedValue: CommonStatusEnum.ENABLE,
          unCheckedValue: CommonStatusEnum.DISABLE,
        },
      },
    },
    {
      field: 'createTime',
      title: $t('common.createTime'),
      minWidth: 180,
      formatter: 'formatDateTime',
    },
    {
      title: $t('common.action'),
      width: 180,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
